import logging
import requests
from bs4 import BeautifulSoup
import pandas as pd
import time
import xml.etree.ElementTree as ET


def get_cid(video_url):
    """
    获取视频的 cid (弹幕 ID)
    """
    import requests
    import re

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/88.0.4324.146 Safari/537.36',
    }
    response = requests.get(video_url, headers=headers)
    if response.status_code != 200:
        raise Exception(f"Failed to fetch video page: {response.status_code}")

    # 使用正则表达式提取 cid
    match = re.search(r'"cid":(\d+)', response.text)
    if match:
        return match.group(1)
    else:
        raise Exception("Failed to find cid in video page")

# 获取弹幕XML数据
def fetch_danmu(cid):
    """
    根据 cid 获取弹幕数据
    """
    url = f"https://api.bilibili.com/x/v1/dm/list.so?oid={cid}"
    print(f"正在爬取：{url}")
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/88.0.4324.146 Safari/537.36',
    }
    response = requests.get(url, headers=headers)
    if response.status_code != 200:
        raise Exception(f"Failed to fetch danmu: {response.status_code}")
    return response.content

def parse_danmu(xml_content):
    """
    解析弹幕 XML 数据
    """
    danmu_list = []
    root = ET.fromstring(xml_content)

    # 弹幕存储在 <d> 标签中
    for d in root.findall("d"):
        attributes = d.attrib
        content = d.text  # 弹幕内容
        p = attributes.get("p", "")
        if p:
            params = p.split(",")
            danmu_list.append({
                "time": float(params[0]),  # 弹幕出现时间 (秒)
                "mode": int(params[1]),  # 弹幕模式
                "font_size": int(params[2]),  # 字体大小
                "color": int(params[3]),  # 颜色 (十进制 RGB)
                "timestamp": int(params[4]),  # 弹幕发送时间戳
                "pool": int(params[5]),  # 弹幕池
                "user_hash": params[6],  # 用户哈希
                "content": content  # 弹幕内容
            })
    return danmu_list


if __name__ == "__main__":
    # video_url = input("请输入 B 站视频链接: ")
    cid = 29625745677
    print(f"视频 cid: {cid}")

    xml_content = fetch_danmu(cid)
    danmu_list = parse_danmu(xml_content)

    # 打印部分弹幕
    for danmu in danmu_list[:10]:  # 打印前 10 条弹幕
        print(danmu)
